#!/usr/bin/env python

import XenAPI
import XenAPIPlugin
import sys
import urllib2
import base64
from xml.dom.minidom import parse

path 	= "/root/PrivacyCA/Repository/txtrepo/"

xmlfile =  path+"schema/xentxtdata.xml"
certblobfile = path+ "Aikpub"
keyfile  = path+"out.pub"
tempxml  = path+"temp.xml"
tempcert = path+"temp.cert"
tempkey =  path+"temp.key"

#all these imports are standard on most modern python implementations
def gen_out_xml():
    dom = parse(xmlfile)
    root = dom.getElementsByTagName("xentxt:xentxtdata")
    xencert = dom.getElementsByTagName('xentxt:xencert')[0]
    xenpub  = dom.getElementsByTagName("xentxt:xenpubkey")[0]
    #print xencert.firstChild.nodeValue
    #print xenpub.firstChild.nodeValue
    f= open (certblobfile)
    cert = base64.b64encode(f.read())
    #print cert
    xencert.firstChild.nodeValue = cert
    f.close()
    f = open(keyfile)
    key = base64.b64encode(f.read())
    xenpub.firstChild.nodeValue = key
    f.close()
    f = open(tempxml,"w");
    #print dom.toxml()
    f.write(dom.toxml())
    f.close()
def read_in_xml():
    dom = parse(tempxml)
    root = dom.getElementsByTagName("xentxt:xentxtdata")
    xencert = dom.getElementsByTagName('xentxt:xencert')[0]
    xenpub  = dom.getElementsByTagName("xentxt:xenpubkey")[0]
    print xencert.firstChild.nodeValue
    print xenpub.firstChild.nodeValue
    f= open (tempcert,"w")
    cert = base64.b64decode(xencert.firstChild.nodeValue)
    f.write(cert)
    f.close()
    f = open(tempkey,"w")
    key = base64.b64decode( xenpub.firstChild.nodeValue)
    f.write(key)
    f.close()
    #print dom.toxml() 

def main(session, args):
    try:
        gen_out_xml()
        f = open(tempxml,"r")
        data = f.read()
        return data
    	#return "success"
    except:
        return "error"

if __name__ == "__main__":
    XenAPIPlugin.dispatch({"main":main})
    #main(None,None)
